package com.cai.servlet.user;

import com.cai.dao.UserDao;
import com.cai.dao.impl.UserDaoImpl;
import com.cai.pojo.UserLogin;
import com.cai.util.CreatCodeUtil;
import com.cai.util.MailMessageUtil;
import com.cai.util.MailUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * @author RuoLi
 */
@WebServlet(name = "ServletUserRegister", value = "/User/UserRegister")
public class ServletUserRegister extends HttpServlet {
    String code = CreatCodeUtil.createCode();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收参数
        String userMail = req.getParameter("UserMail");
        String userPassword=req.getParameter("UserPassword");
        System.out.println(userMail+userPassword);
        sendAccount(userPassword,userMail);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收参数
        String userCode=req.getParameter("code");
        if (!Objects.equals(code, userCode)){
            resp.getWriter().println(-1);
        }else {
            resp.getWriter().println(1);
        }
    }

    //发送信息
    public  void sendAccount(String userPassword,String userMail){
        UserDao userDao=new UserDaoImpl();
        UserLogin userLogin=new UserLogin();
        //生成新账号
        userLogin.setLogin_password(userPassword);
        userLogin.setLogin_Mail(userMail);
        int account= userDao.insertUser(userLogin);
        //发送到邮箱
        //调用随机验证码方法
        MailMessageUtil messageUtil = new MailMessageUtil();
        MailUtil.sendMail(messageUtil.sendCodeMessage(userMail, code, String.valueOf(account)));
        //逻辑问题 用户接收验证码后还会接收到账号，此时账号应该为未激活状态
    }
}
